package com.mouse.magent.common.codec;

import com.mouse.magent.common.protocol.Command;
import com.mouse.magent.common.protocol.Message;
import com.mouse.magent.common.util.JsonUtil;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;
import io.netty.util.CharsetUtil;
import lombok.extern.slf4j.Slf4j;

import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;

/**
 * 反序列化
 */
@Slf4j
public class MessageEncoder extends MessageToByteEncoder<Message> {

    @Override
    protected void encode(ChannelHandlerContext ctx, Message msg, ByteBuf out) throws Exception {

        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        int length = 0;
        try (DataOutputStream dataOutputStream = new DataOutputStream(byteArrayOutputStream)) {

            Command messageType = msg.getType();
            dataOutputStream.writeInt(messageType.getCode());

            byte[] metaDataBytes = JsonUtil.toJson(msg.getHeader()).getBytes(CharsetUtil.UTF_8);
            dataOutputStream.writeInt(metaDataBytes.length);
            dataOutputStream.write(metaDataBytes);

            if (msg.getData() != null && msg.getData().length > 0) {
                dataOutputStream.write(msg.getData());
            }


            byte[] data = byteArrayOutputStream.toByteArray();
            length = data.length;
            out.writeInt(data.length);
            out.writeBytes(data);
        }
        msg.setData(null);
        log.info("message发送：{} data大小:{}", JsonUtil.toJson(msg), length);
    }

}
